package com.glorysoft.knowlespda.base;

import android.annotation.SuppressLint;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.BitmapFactory;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentController;
import androidx.fragment.app.FragmentManager;

import com.glorysoft.knowlespda.R;
import com.glorysoft.knowlespda.entity.HomeEntity;
import com.glorysoft.knowlespda.entity.net.BaseRequestBean;
import com.glorysoft.knowlespda.entity.net.BaseResponseBean;
import com.glorysoft.knowlespda.entity.net.HeaderBean;
import com.glorysoft.knowlespda.entity.net.NetRequestBean;
import com.glorysoft.knowlespda.ui.login.view.LoginActivity;
import com.glorysoft.knowlespda.ui.track.view.TrackActivity;
import com.glorysoft.knowlespda.ui.track.view.TrackOutActivity;
import com.glorysoft.knowlespda.ui.track.view.TracksferActivity;
import com.glorysoft.knowlespda.utils.ChangeLanguageHelper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_InitUtils;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_NetUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_SharePreferencesUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;

import org.apache.commons.lang3.StringEscapeUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import rxhttp.wrapper.cookie.CookieStore;
import rxhttp.wrapper.param.RxHttp;
import rxhttp.wrapper.ssl.HttpsUtils;


/**
 * FileName: MyApp
 * Author: XJH
 * Date: 2020/5/12 11:30
 * Description:
 * History:
 */
public class MyApp extends Application {

    public static Context app;
    public static FragmentManager supportFragmentManager;
    private static MyApp instance;
    private static PendingIntent pi;
    private static NotificationManager notificationManager;
    private static int post = 0;
    private static Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            Log.e("TIMER", "run:  + 收到消息" );
            FreeUI_EntityCallBack<BaseResponseBean<HomeEntity>> callBack = new FreeUI_EntityCallBack<BaseResponseBean<HomeEntity>>
                    (new TypeToken<BaseResponseBean<HomeEntity>>() {
                    }.getType()) {

                @RequiresApi(api = Build.VERSION_CODES.O)
                @Override
                public void onSuccess(Response<BaseResponseBean<HomeEntity>> response) {
                    if (response.body().getCode() != 0){
                        Toast.makeText(app,response.body().getMessage(),Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (response.body().getData().getBody().getNOTICELIST().size() > 0){
                        List<HomeEntity.NoticeEntity> listitme = response.body().getData().getBody().getNOTICELIST();
                        for (int i=0; i<listitme.size(); i++) {
                            Intent intent = null;
                            if (listitme.get(i).getNOTICETYPE().contains("ReplaceIn")){
                                intent = new Intent(app, TrackActivity.class);

                            }else if (listitme.get(i).getNOTICETYPE().contains("ReplaceOut")){
                                intent = new Intent(app, TrackOutActivity.class);
                            }else {
                                intent = new Intent(app, TracksferActivity.class);
                            }
                            intent.putExtra("DATA",listitme.get(i).getMACHINEID());
                            pi = PendingIntent.getActivity(app, UUID.randomUUID().hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                Notification notification = new Notification.Builder(app, "defaultss")
                                        .setContentTitle(listitme.get(i).getMACHINEID())
                                        .setContentText(listitme.get(i).getMESSAGE())
                                        .setWhen(System.currentTimeMillis())
                                        .setSmallIcon(R.mipmap.ic_launcher)
                                        .setAutoCancel(true)
                                        .setContentIntent(pi)
                                        .build();
                                notification.flags = Notification.FLAG_AUTO_CANCEL;
                                notificationManager.notify(post++, notification);
                            }else {
                                Notification notification = new Notification.Builder(app)
                                        .setContentTitle(listitme.get(i).getMACHINEID())
                                        .setContentText(listitme.get(i).getMESSAGE())
                                        .setWhen(System.currentTimeMillis())
                                        .setSmallIcon(R.mipmap.ic_launcher)
                                        .setAutoCancel(true)
                                        .setContentIntent(pi)
                                        .build();
                                notification.flags = Notification.FLAG_AUTO_CANCEL;
                                notificationManager.notify(post++, notification);
                            }

                        }
                    }

                    Log.e("TIMER", "run:  + 接收成功" );


                }

                @Override
                public void onError
                        (Response<BaseResponseBean<HomeEntity>> response) {
                    super.onError(response);
                }
            };
            JsonObject map = new JsonObject();
            map.addProperty("OPID",Constant.Companion.getCURRENT_USER());
            map.addProperty("PDANO",Constant.Companion.getPDA_NO());
            NetRequestBean format = new NetRequestBean<>();
            format.setBody(map);
            format.setHeader(new HeaderBean("GetCurrentNotice"));
            BaseRequestBean message = new BaseRequestBean();
            message.setRequest(format);
            HashMap<String, String> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("requestMessage", StringEscapeUtils.unescapeJson(new Gson().toJson(message)));
            Log.e("TIMER", "run:  =="  + StringEscapeUtils.unescapeJson(new Gson().toJson(message)));
            FreeApi_LogUtils.saveErrorMessages(StringEscapeUtils.unescapeJson(new Gson().toJson(message)),"请求JSON");
            FreeApi_NetUtils.requestPostNet(Constant.Companion.getREQUEST_URL_DEBUG(), this, objectObjectHashMap, callBack);
            super.handleMessage(msg);
        }
    };

    public static MyApp getInstance() {
        return instance;
    }

    public static FragmentManager getSupportFragmentManager() {
        return supportFragmentManager;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        app = getApplicationContext();
        FreeUI_InitUtils.init(getApplicationContext(), this, false, 60 * 1000L, 0);
        FreeUI_InitUtils.setTheme(FreeApi_StaticMembers.THEME_GLORY);
        initRxHttp(60);

        Constant.Companion.setIMEI_ID(getMacAddress());

//        TelephonyManager telMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
//        FreeApi_LogUtils.saveErrorMessages(telMgr.getDeviceId(),"唯一的设备ID");

        //8.0 以后需要加上channelId 才能正常显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            String channelId = "defaultss";
            String channelName = "默认通知";
            createNotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        }

    }

    private String getMacAddress(){
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            return getMacDefault();
        }else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N){
            return getMacAddressM();
        }

        return getMacFromHardware();

    }

    private String getMacDefault(){
        String address = "未获取到MAC地址";
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        String macAddress = connectionInfo.getMacAddress();
        address = macAddress.toUpperCase(Locale.ENGLISH);
        return address;
    }

    private String getMacAddressM(){
        String address = "未获取到MAC地址";
        try {
            address = new BufferedReader(new FileReader("/sys/class/net/wlan0/address")).readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return address;
    }

    private String getMacFromHardware(){
        try {
            ArrayList<NetworkInterface> list = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : list) {
                if (!"wlan0".equalsIgnoreCase(nif.getName())) {
                    continue;
                }
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null || macBytes.length == 0) {
                    continue;
                }
                StringBuilder result = new StringBuilder();
                for (byte b : macBytes) {
                    result.append(String.format("%02X", b));
                }
                return result.toString().toUpperCase();

            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "未获取到MAC地址";
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        // 创建 channel
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        // 获取 notificationManager
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // 注册 channel
        notificationManager.createNotificationChannel(channel);
    }

    public static TimerTask showTimer(Timer timer) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
                Log.e("TIMER", "run:  + 发出消息" );
            }
        };
        timer.schedule(task, new Date(), 3000);
        return task;
    }

    private void initRxHttp(int timeOut) {
        File file = new File(getExternalCacheDir(), "RxHttpCookie");
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
        OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(new CookieStore(file))
                .connectTimeout(timeOut, TimeUnit.SECONDS)
                .readTimeout(timeOut, TimeUnit.SECONDS)
                .writeTimeout(timeOut, TimeUnit.SECONDS)
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager) //添加信任证书
                .hostnameVerifier((hostname, session) -> true) //忽略host验证
                .build();
        //RxHttp初始化，自定义OkHttpClient对象，非必须
        RxHttp.init(client);
        RxHttp.setDebug(true);
        RxHttp.setOnParamAssembly(p -> {
            /*根据不同请求添加不同参数，子线程执行，每次发送请求前都会被回调
            如果希望部分请求不回调这里，发请求前调用Param.setAssemblyEnabled(false)即可
             */
            return p; //添加公共请求头
        });
    }

    public static void stopTimer(TimerTask task,Timer timer){
        //关闭定时任务
        timer.cancel();
        task.cancel();
        Log.e("TIMER", "run:  + 关闭消息" );
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        String LANGUAGE = FreeApi_SharePreferencesUtils.getSharePre("KNOWLES_FILE", "LANGUAGE", "中文", this);
        switch (LANGUAGE) {
            case "中文":
            case "Chinese":
                ChangeLanguageHelper.changeAppLanguage(this, Locale.SIMPLIFIED_CHINESE, "");
                break;
            case "英语":
            case "English":
                ChangeLanguageHelper.changeAppLanguage(this, Locale.ENGLISH, "");
                break;
        }
    }
}
